﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Luna.Connectors.ZohoCRM
{
    public sealed class ZohoInsertResponse : ZohoResponse
    {
        private readonly List<RecordDetail> DETAILS = new List<RecordDetail>();

        internal ZohoInsertResponse(string P_Module, string P_Method, string P_ResponseContent)
            : base(P_Module, P_Method, P_ResponseContent)
        {
        }

        public IEnumerable<RecordDetail> RecordDetails
        {
            get { return DETAILS.AsReadOnly(); }
        }

        internal override void LoadResultFromXml(XElement P_ResultElement)
        {
            var L_Details = P_ResultElement.Descendants(SerializerParams.ELEMENT_RECORD_DETAIL);
            foreach (var L_Element in L_Details)
            {
                var L_DetailElements = L_Element.Descendants();
                var L_RecordDetail = new RecordDetail();

                foreach (var L_DetailElement in L_DetailElements)
                {
                    var L_DetailKey = L_DetailElement.Attribute(SerializerParams.ATTRIBUTE_VALUE).Value;
                    var L_DetailValue = L_DetailElement.Value;

                    if (L_DetailKey == SerializerParams.DETAIL_VALUE_ID)
                    {
                        L_RecordDetail.ID = L_DetailValue;
                    }
                    else if (L_DetailKey == SerializerParams.DETAIL_VALUE_CREATED)
                    {
                        DateTime L_CreatedDate;
                        if (DateTime.TryParse(L_DetailValue, out L_CreatedDate))
                        {
                            L_RecordDetail.CreatedDate = L_CreatedDate;
                        }
                    }
                    else if (L_DetailKey == SerializerParams.DETAIL_VALUE_MODIFIED)
                    {
                        DateTime L_ModifiedDate;
                        if (DateTime.TryParse(L_DetailValue, out L_ModifiedDate))
                        {
                            L_RecordDetail.ModifiedDate = L_ModifiedDate;
                        }
                    }
                    else if (L_DetailKey == SerializerParams.DETAIL_VALUE_CREATED_BY)
                    {
                        L_RecordDetail.CreatedBy = L_DetailValue;
                    }
                    else if (L_DetailKey == SerializerParams.DETAIL_VALUE_MODIFIED_BY)
                    {
                        L_RecordDetail.ModifiedBy = L_DetailValue;
                    }
                }

                DETAILS.Add(L_RecordDetail);
            }
        }
    }
}